package in.co.codedoc.idcontainer;

import in.co.codedoc.idcontainer.IdContainer.IdContainerId;
import in.co.codedoc.sql.DBMappedEntity;
import in.co.codedoc.sql.IDBase;

import java.util.Iterator;
import java.util.TreeSet;

public class IdSet<T extends IDBase>
	implements DBMappedEntity
{
	public IdSet<T> SetId(IdSetId<T> id)
	{
		this.id = id;
		
		return this;
	}

	public IdSetId<T> GetId()
	{
		if(id == null)
		{
			Save();
		}
		
		return id;
	}
	
	@Override
	public void Reload()
	{
		IdContainer idContainer 
			= IdContainerId.Create(id.GetId()).Get();
		
		container.clear();
		
		idContainer.Copy(container);
	}
	
	public boolean Contains(T t)
	{
		return container.contains(t.GetId());
	}
	
	public IdSet<T> Remove(T t)
	{
		if(container.contains(t.GetId()))
		{
			id = null;
			container.remove(t.GetId());
		}
		return this;
	}
	
	public IdSet<T> Add(T t)
	{
		if(!container.contains(t.GetId()))
		{
			id = null;
			container.add(t.GetId());
		}
		return this;
	}
	
	public IdSet<T> Save()
	{
		if(id == null)
		{
			IdContainer idContainer
				= IdContainer.BindOrSave(container);
			
			id = IdSetId.Create(idContainer.GetId().GetId());
		}
		
		return this;
	}
	
	public Iterator<Long> iterator()
	{
		return container.iterator();
	}
	
	private IdSetId<T> id;
	private TreeSet<Long> container = new TreeSet<Long>();
}
